package routes

import (
	"net/http"
	"strconv"
	"time"

	"codeberg.org/vnpower/pixivfe/v2/audit"
	"codeberg.org/vnpower/pixivfe/v2/core"
	"go.uber.org/zap"
)

type userPageData struct {
	user     core.User
	category core.UserWorkCategory
	page     int
}

func fetchData(auditor *audit.Auditor, r *http.Request, getTags bool) (userPageData, error) {
	id := GetPathVar(r, "id")
	if _, err := strconv.Atoi(id); err != nil {
		return userPageData{}, err
	}

	categoryValue := GetPathVar(r, "category", core.CategoryAny.Value)
	category := core.NewUserWorkCategory(categoryValue)
	err := category.Validate()
	if err != nil {
		return userPageData{}, err
	}

	page := GetQueryParam(r, "page", "1")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		return userPageData{}, err
	}

	user, err := core.GetUserProfile(auditor, r, id, &category, pageInt, getTags)
	if err != nil {
		return userPageData{}, err
	}

	// NOTE: these values are now calculated in core/user, scoped per category
	// var worksPerPage float64
	// if category.value == core.CategoryBookmarks.value {
	// 	worksPerPage = 48.0
	// } else {
	// 	worksPerPage = 30.0
	// }

	// worksCount := user.CategoryItemCount
	// pageLimit := int(math.Ceil(float64(worksCount) / worksPerPage))
	// category.SetPageLimit(pageLimit)

	return userPageData{
		user:     user,
		category: category,
		page:     pageInt,
	}, nil
}

func UserPage(auditor *audit.Auditor, w http.ResponseWriter, r *http.Request) error {
	data, err := fetchData(auditor, r, true)
	if err != nil {
		return err
	}

	auditor.Logger.Debug("Category details",
		zap.String("category", data.category.Value),
		zap.Int("pageLimit", data.category.PageLimit),
	)

	return RenderHTML(w, r, Data_user{
		Title:     data.user.Name,
		User:      data.user,
		Category:  data.category,
		Page:      data.page,
		MetaImage: data.user.BackgroundImage,
	})
}

func UserAtomFeed(auditor *audit.Auditor, w http.ResponseWriter, r *http.Request) error {
	data, err := fetchData(auditor, r, false)
	if err != nil {
		return err
	}

	return RenderWithContentType(w, r, "application/atom+xml", Data_userAtom{
		URL:      r.RequestURI,
		Title:    data.user.Name,
		User:     data.user,
		Category: data.category,
		Updated:  time.Now().Format(time.RFC3339),
		Page:     data.page,
	})
}
